<?php
/***
 * Candy框架 数据库备份还原类
 * 
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2019-08-05 10:48:32 $   
 */
 
declare(strict_types=1);
namespace Candy\Extend\DB;
use Candy\Core\Tpl;

class DBService {
    /**
     * 备份文件信息 part - 卷号，name - 文件名
     * @var array
     */
    private $file;

    /**
     * 当前打开文件大小
     * @var integer
     */
    private $size = 0;

    /**
     * 备份配置
     * @var array
     */
    private $config;
	
	/**
     * 文件指针
     * @var resource
     */
    private $fp;
	
	/**
     * 数据库对象
     * @var resource
     */
    private $db;
	
	/**
     * 表前缀
     * @var resource
     */
    private $tabPreFix;
	
	/**
     * 数据库表列表
     * @var resource
     */
    private $tableList = [];
	
	/**
     * 执行顺序
     * @var resource
     */
    private $order = 0;
	
	/**
     * 初始化
     * @var resource
     */
    private $init = 0;

    /**
     * 数据库备份构造方法
	 *
     * @param array  $file   备份或还原的文件信息
     * @param array  $config 备份配置信息
     * @param string $type   执行类型，export - 备份数据， import - 还原数据
	 *	$config = array(
	 *		'path'     => './', //备份文件目录
	 *		'part'     => 3145728, //3MB
	 *		'compress' => 0,    //是否压缩
	 *		'level'    => 4,	//压缩水平
     *    );
	 * N('DB\\DBService',[['name'=>'test','part'=>0], $config])
     */
    public function __construct(array $file = [],array $config = [],string $type = 'export')
	{
        $this->file   = $file;
        $this->config = $config;
        $this->db = D();
        $this->tabPreFix = G('TABPREFIX');
    }

    /**
     * 打开一个卷，用于写入数据
	 *
     * @param  integer $size 写入数据的大小
     */
    private function open(int $size = 0): void
	{
        if($this->fp){
            $this->size += $size;
            if($this->size > $this->config['part']){
                $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
                $this->fp = null;
                $this->file['part']++;
                $_SESSION['backup_file'] = $this->file;
                $this->create();
            }
        } else {
            $backuppath = $this->config['path'];
            $filename   = "{$backuppath}{$this->file['name']}-{$this->file['part']}.sql";
            if($this->config['compress']){
                $filename = "{$filename}.gz";
                $this->fp = @gzopen($filename, "a{$this->config['level']}");
            } else {
                $this->fp = @fopen($filename, 'a');
            }
            $this->size = filesize($filename) + $size;
        }
    }

    /**
     * 写入初始数据
	 *
     * @return boolean true - 写入成功，false - 写入失败
     */
    private function create(): bool
	{
        $sql  = "-- -----------------------------\n";
        $sql .= "-- Candy MySQL Data Transfer \n";
        $sql .= "-- \n";
        $sql .= "-- Host     : " . G('HOST') . "\n";
        $sql .= "-- Database : " . G('DBNAME') . "\n";
        $sql .= "-- \n";
        $sql .= "-- Part : #{$this->file['part']}\n";
        $sql .= "-- Date : " . date("Y-m-d H:i:s") . "\n";
        $sql .= "-- -----------------------------\n\n";
        $sql .= "SET FOREIGN_KEY_CHECKS = 0;\n\n";
        return $this->write($sql);
    }

    /**
     * 写入SQL语句
	 *
     * @param  string $sql 要写入的SQL语句
     * @return boolean     true - 写入成功，false - 写入失败！
     */
    private function write(string $sql): bool
	{
        $size = strlen($sql);
        
        //由于压缩原因，无法计算出压缩后的长度，这里假设压缩率为50%，
        //一般情况压缩率都会高于50%；
        $size = $this->config['compress'] ? $size / 2 : $size;
        
        $this->open($size); 
        return $this->config['compress'] ? @gzwrite($this->fp, $sql) : @fwrite($this->fp, $sql);
    }

    /**
     * 获取数据库所有表名
	 *
     * @param  string $sql 要写入的SQL语句
     * @return boolean     true - 写入成功，false - 写入失败！
     */
    private function getTableList(): void
	{
		if(count($this->tableList) == 0){
			$tableList = $this->db->query('select TABLE_NAME from INFORMATION_SCHEMA.Tables where table_schema = \''. G('DBNAME') .'\'', 'select');
			if(count($tableList) > 0){
				$tableNameList = [];
				foreach($tableList as $table){
					$tableNameList[] = $table['TABLE_NAME'];
				}
				
				$this->tableList = $tableNameList;
				$this->order = 0;
			}
		}
    }

    /**
     * 备份表结构
	 *
     * @param  string  $table 表名
     * @param  integer $start 起始行数
     * @return boolean        false - 备份失败
     */
    public function backup(string $table = '',int $start = 0): bool
	{
		//初始化
		if($this->init == 0){
			$this->init = 1;
			if(false === $this->create()){
                Tpl::shutDownTpl('文件写入失败，请检查权限！');
            }
		}
		
		//获取处理的表名
		if(empty($table)){
			//整理库表
			$this->getTableList();
			$table = $this->tableList[$this->order] ?: '';
		}else{
			$table = (stripos($table, $this->tabPreFix) === false ? $this->tabPreFix : '') . $table;
		}
		
		//没有表表示完成
		if(empty($table)){
			return true;
		}
		
		//结束
		if(!empty($table)){
			//备份表结构
			if(0 == $start){
				$result = $this->db->query("SHOW CREATE TABLE `{$table}`", 'find');
				$result = array_change_key_case($result,CASE_LOWER); //数组小写化
				$sql  = "\n";
				$sql .= "-- -----------------------------\n";
				$sql .= "-- Table structure for `{$table}`\n";
				$sql .= "-- -----------------------------\n";
				$sql .= "DROP TABLE IF EXISTS `{$table}`;\n";
				$sql .= trim($result['create table']) . ";\n\n";
				$this->write($sql);
			}
			
			//数据总数
			$count = $this->db->query("SELECT COUNT(*) AS count FROM `{$table}`", 'total');
				
			//备份表数据
			if($count){
				//写入数据注释
				if(0 == $start){
					$sql  = "-- -----------------------------\n";
					$sql .= "-- Records of `{$table}`\n";
					$sql .= "-- -----------------------------\n";
					$this->write($sql);
				}

				//备份数据记录
				$result = $this->db->query("SELECT * FROM `{$table}` LIMIT {$start}, 1000", 'select');
				foreach ($result as $row) {
					$sql = "INSERT INTO `{$table}` VALUES (";
					foreach($row as $v){
						$sql .= "'".str_replace("\r\n", '\r\n', addslashes($v))."',";
					}
					$sql = trim($sql, ',').");\n";
					$this->write($sql);
				}

				//还有更多数据
				if($count > $start + 1000){
					$this->backup($table, $start + 1000);
				}
			}
			
			
			//备份下一表
			if($this->order < count($this->tableList) && $start == 0){
				$this->order++;
				$this->backup();
			}else{
				return true;
			}
		}
    }

    /**
     * 还原数据
	 *
     * @param  integer $start 起始行数
     * @return boolean        false - 还原失败
     */
    public function import(string $file = '',int $start = 0): bool
	{
		if(empty($file)){
			$path  = $this->config['path'] . $this->file['name'] . '-*.sql*';
			$files = glob($path);
		}else{
			$files = [$file];
		}
		
		if(count($files) > 0){
			foreach($files as $file){
				if($this->config['compress']){
					$gz   = gzopen($file, 'r');
					$size = 0;
				} else {
					$size = filesize($file);
					$gz   = fopen($file, 'r');
				}
				
				$sql  = '';
				if($start){
					$this->config['compress'] ? gzseek($gz, $start) : fseek($gz, $start);
				}
				
				//开始导入
				while($line = $this->config['compress'] ? gzgets($gz) : fgets($gz)){
					$sql .= $line;
					if(preg_match('/.*;$/', trim($sql))){
						if(false !== $this->db->query($sql, 'other')){
							$start += strlen($sql);
						} else {
							Tpl::shutDownTpl('SQL命令执行失败，请检查权限！');
						}
					}
				}
			}
		}
		
		return true;
    }
	
    /**
     * 优化表
     */
    public function optimize(array $tables = []): void
	{
        if(empty($tables)){
			$this->getTableList();
			$tables = implode(',', $this->tableList);
		}else{
			$tables = implode(',', $tables);
		}
		
		$this->db->query('OPTIMIZE TABLE '.$this->_safe_replace($tables));
    }
	
    /**
     * 修复表
     */
    public function repair(array $tables = []): void
	{
        if(empty($tables)){
			$this->getTableList();
			$tables = implode(',', $this->tableList);
		}else{
			$tables = implode(',', $tables);
		}
		
		$this->db->query('REPAIR TABLE '.$this->_safe_replace($tables));
    }
	
    /**
     * 表结构
     */
    public function structure(string $table = ''): string
	{
		if(empty($table)) return '';
		
        $result = $this->db->query("SHOW CREATE TABLE `{$table}`", 'find');
		$result = array_change_key_case($result,CASE_LOWER); //数组小写化
		
		return $result['create table'];
    }
	 
	/**
	 * 清空表		 
	 */
	public function truncate(string $table = ''): void
	{
		if(!empty($table))
			$this->db->query('TRUNCATE '.$this->_safe_replace($table));
	}
	
	/**
	 * 删除表		 
	 */
	public function delete(string $table = ''): void
	{
		if(!empty($table))
			$this->db->query('DELETE '.$this->_safe_replace($table));
	}
	
	/**
     * 安全替换
     */
	private function _safe_replace(string $string): string
	{
		return str_replace(array('`',"\\",'&',' ',"'",'"','/','*','<','>',"\r","\t","\n","#"), '', $string);
	}

    /**
     * 析构方法，用于关闭文件资源
     */
    public function __destruct()
	{
        if(!is_null($this->fp)){
            $this->config['compress'] ? @gzclose($this->fp) : @fclose($this->fp);
        }
    }
}
